package com.mhc.suzuki.service.impl;

import com.alibaba.fastjson.JSON;
import com.mhc.haval.api.dto.StaffRoleDTO;
import com.mhc.haval.api.service.IStaffDeptService;
import com.mhc.haval.api.service.IStaffRoleService;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.AuditTaskBO;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.RoleTypeEnum;
import com.mhc.suzuki.dal.mapper.ext.OrderAuditTaskExtMapper;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.service.RandomExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by HMJ on 2017/10/24.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class RandomExecutorServiceImpl implements RandomExecutorService {

    @Autowired
    private IStaffRoleService staffRoleService;
    @Autowired
    private IStaffDeptService staffDeptService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderAuditTaskExtMapper orderAuditTaskExtMapper;

    /**
     * 审核分配原则
     * @param roleCodeStr
     * @param logedUser
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public String randomExecutor(String roleCodeStr,User logedUser) throws SuzukiCommonException {
        /**截取字符串获取角色名称**/
        log.info("开始截取角色名称...");
        String newStr = roleCodeStr.substring(4, roleCodeStr.indexOf("Id"));
        String roleCode = "ROLE_" + newStr.toUpperCase();
        log.info("开始分配任务,下个节点执行角色为：{}", roleCode);
        /**当角色是业务经理**/
        if(RoleTypeEnum.ROLE_SALESMANAGER.getCode().equals(roleCode)){
            /**获取当前用户的部门信息**/
            Long deptId = logedUser.getDeptId();
            log.info("当前员工角色为：{},所在部门为：{}--{}", logedUser.getRoleList().get(0), logedUser.getDeptId(), logedUser.getDeptName());
            log.info("正在查询所属业务经理...");
            List<StaffRoleDTO> salesManagerList = staffDeptService.selectStaffByDept(deptId,RoleTypeEnum.ROLE_SALESMANAGER.getCode());
            if(CollectionUtils.isEmpty(salesManagerList)){
                log.error("查不到对应的业务经理...");
                throw new SuzukiCommonException(ErrorCodeEnum.SALESMANAGER_LIST_ERROR);
            }
            log.info("当前业务员所属业务经理为:{}--{}",salesManagerList.get(0).getStaffId(),salesManagerList.get(0).getStaffName());
            return String.valueOf(salesManagerList.get(0).getStaffId());
        }
        /**当角色是审核员**/
        else if(RoleTypeEnum.ROLE_AUDITOR.getCode().equals(roleCode)){


          return  this.randomAuditor(roleCode);

        }
        /**其他**/
        else{
            log.info("正在查询{}列表",roleCode);
            List<StaffRoleDTO> list = staffRoleService.selectStaffByRole(roleCode);
            log.info("当前角色下拥有执行人信息如下：{}", JSON.toJSONString(list));
            if (CollectionUtils.isEmpty(list)) {
                log.error("查不到执行人列表...");
                throw new SuzukiCommonException(ErrorCodeEnum.OTHER_LIST_ERROR);
            }
            log.info("当前角色下包含{}名员工...", list.size());
            log.info("执行以少分配原则开始分配任务...");
            /**分别查询每人目前所处理的任务数**/
            String approveStaffId = null;
            int minCount = Integer.MAX_VALUE;    //初始值为最大
            for (int i = 0; i < list.size(); i++) {
                int count = orderAuditTaskExtMapper.countByTaskNum(list.get(i).getStaffId());
                if (count < minCount) {
                    minCount = count;
                    approveStaffId = String.valueOf(list.get(i).getStaffId());
                }
            }
            log.info("分配任务结束，执行人编号为：{}", approveStaffId);
            return approveStaffId;
        }
    }



    public String randomAuditor (String roleCodeStr){

        BigDecimal minAmount = new BigDecimal("300000.0000");
        BigDecimal maxAmount = new BigDecimal("500000.0000");

        log.info("正在查询审核员列表...");
        List<StaffRoleDTO> auditorList = staffRoleService.selectStaffByRole(roleCodeStr);
        log.info("当前角色下拥有执行人信息如下：{}", JSON.toJSONString(auditorList));
        if(CollectionUtils.isEmpty(auditorList)){
            log.error("查不到审核员列表...");
            throw new SuzukiCommonException(ErrorCodeEnum.AUDITOR_LIST_ERROR);
        }
        Map<Long, Integer> paramMap = new TreeMap();
        int staffTaskWeights = 0;
        int taskWeights = 0;
        for(int i=0;i<auditorList.size();i++){
            List<AuditTaskBO> auditTaskList = orderAuditTaskExtMapper.getExecutorTaskList(auditorList.get(i).getStaffId());
            for(int j = 0 ;j<auditTaskList.size();j++){
                log.info("任务id{}-贷款金额{}",auditTaskList.get(j).getTaskId(),auditTaskList.get(j).getLoanAmount());
                /**小于30w**/
                if(auditTaskList.get(j).getLoanAmount().compareTo(minAmount)==-1){
                    log.info("小于30w");
                    taskWeights = 1;
                }
                /**大于等于30w,小于50w**/
                else if(auditTaskList.get(j).getLoanAmount().compareTo(minAmount)== 0 ||
                        auditTaskList.get(j).getLoanAmount().compareTo(minAmount)== 1 ||
                        auditTaskList.get(j).getLoanAmount().compareTo(maxAmount)== -1){
                    log.info("大于等于30w,小于50w");
                    taskWeights = 2;
                }
                /**大于等于50w**/
                else if(auditTaskList.get(j).getLoanAmount().compareTo(maxAmount)==1){
                    log.info("大于等于50w");
                    taskWeights = 3;
                }
                staffTaskWeights = staffTaskWeights + taskWeights;
                log.info("人员-权重：{}-{}",auditorList.get(i).getStaffId(),staffTaskWeights);
            }
            paramMap.put(auditorList.get(i).getStaffId(),staffTaskWeights);
        }


        //将Map转为List
        List<Map.Entry<Long, Integer>> list = new ArrayList<>(paramMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Long, Integer>>() {
            @Override
            public int compare(Map.Entry<Long, Integer> o1, Map.Entry<Long, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        String randomAuditorId = null;
        if(CollectionUtils.isNotEmpty(list)) {
            randomAuditorId = String.valueOf(list.get(0).getKey());
        }

        return  randomAuditorId;
    }


}
